package com.ezia.coreservices.charging.jwt;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.HmacUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ezia.coreservices.charging.config.JwtConfig;
import com.ezia.coreservices.charging.config.MobilityAsiaConfig;
import com.ezia.coreservices.charging.config.StarCharingConfig;
import com.ezia.coreservices.charging.controller.TestController;
import com.ezia.coreservices.charging.dao.UserInfoDao;
import com.ezia.coreservices.charging.entity.UserInfoEntity;
import com.ezia.coreservices.charging.utils.AesEncryptionUtil;
import com.ezia.coreservices.charging.utils.MyUtils;
import com.ezia.coreservices.charging.utils.ResultMsg;
import com.ezia.coreservices.charging.utils.ResultStatusCode;

import net.sf.json.JSONObject;


@RestController
public class JsonWebToken {
	
	private static final Logger logger = LoggerFactory.getLogger(JsonWebToken.class);

	@Autowired
	private UserInfoDao userinfodao;
	
	@Autowired
	private JwtConfig jwtconfig;
	
	@Autowired
	private StarCharingConfig starcharingconfig;
	
	@Autowired
	private AesEncryptionUtil aesencryptionutil;
	
	@Autowired
	private MobilityAsiaConfig mobilityasiaconfig;

	
	
	/**
	 * 手机APP获取token
	 *
	 * 
	 * @param token
	 * @return 
	 * add by yc
	 */
	@RequestMapping("oauth/token")
	public Object getAccessToken(@RequestBody LoginPara loginPara) {
		ResultMsg resultMsg;
		try {
			if (loginPara.getClientId() == null
					|| (loginPara.getClientId().compareTo(jwtconfig.getClientId()) != 0)) {
				resultMsg = new ResultMsg(ResultStatusCode.Invalid_Client.getRespCode(),
						ResultStatusCode.Invalid_Client.getRespMsg(), null);
				return resultMsg;
			}


			// 验证用户名密码
			UserInfoEntity user = userinfodao.findUserInfoByName(loginPara.getUserName());
			if (user == null) {
				resultMsg = new ResultMsg(ResultStatusCode.Invalid_Password.getRespCode(),
						ResultStatusCode.Invalid_Password.getRespMsg(), null);
				return resultMsg;
			} else {
				String md5Password = MyUtils.getMD5(loginPara.getPassword() + user.getSalt());
				if (md5Password.compareTo(user.getPassword()) != 0) {
					resultMsg = new ResultMsg(ResultStatusCode.Invalid_Password.getRespCode(),
							ResultStatusCode.Invalid_Password.getRespMsg(), null);
					return resultMsg;
				}
			}

			// 拼装accessToken
			String accessToken = JwtHelper.createJWT(loginPara.getUserName(), String.valueOf(user.getName()),
					user.getRole(), jwtconfig.getClientId(), jwtconfig.getName(),
					jwtconfig.getExpiresSecond() * 1000, jwtconfig.getBase64Secret());

			// 返回accessToken
			AccessToken accessTokenEntity = new AccessToken();
			accessTokenEntity.setAccess_token(accessToken);
			accessTokenEntity.setExpires_in(jwtconfig.getExpiresSecond());
			accessTokenEntity.setToken_type("bearer");
			resultMsg = new ResultMsg(ResultStatusCode.Success.getRespCode(), ResultStatusCode.Success.getRespMsg(),
					accessTokenEntity);
			return resultMsg;

		} catch (Exception ex) {
			resultMsg = new ResultMsg(ResultStatusCode.Server_Error.getRespCode(), ResultStatusCode.Server_Error.getRespMsg(),
					null);
			return resultMsg;
		}
	}
	
	/**
	 * 互联互通推送获取token接口
	 * 
	 * @param token
	 * @return 
	 * add by yc
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "query_token",method = RequestMethod.POST)
	public Object query_token(@RequestBody String RequestData) throws Exception {
		logger.info("进入获取token接口");
		logger.info(RequestData);
		JSONObject resultMsg = new JSONObject();
		JSONObject requestData = JSONObject.fromObject(RequestData);
		Map<String, Object> mResponse = (Map<String, Object>) JSONObject.fromObject(requestData.toString());
		mResponse.put("Data", aesencryptionutil.decryptData(mResponse.get("Data").toString(), mobilityasiaconfig.getDataSecret(),mobilityasiaconfig.getDataSecretIV()));
		Map<String, Object> mData = (Map<String, Object>) JSONObject.fromObject(mResponse.get("Data").toString());
		UserInfoEntity user = userinfodao.findUserInfoByName(mData.get("OperatorID").toString());
		if (user == null) {
			resultMsg.put("OperatorID", "313744932");
			resultMsg.put("SuccStat", 1);
			resultMsg.put("FailReason", 1);
			Map<String, Object> mEncryptData = new HashMap<String, Object>();
			mEncryptData.putAll(resultMsg);
			String newdata = aesencryptionutil.encryptData(mEncryptData,mobilityasiaconfig.getDataSecret(),mobilityasiaconfig.getDataSecretIV());
			Map<String, Object> mRequest = new HashMap<String, Object>();
			mRequest.put("Ret", 0);
			mRequest.put("Data", newdata);
			mRequest.put("Msg", "");
			mRequest.put("Sig", HmacUtils.hmacMd5Hex(mobilityasiaconfig.getSigSecret(), 0 + "" + newdata).toUpperCase());
			JSONObject result = JSONObject.fromObject(mRequest);
			return result;
		} else {
			String md5Password = MyUtils.getMD5(mData.get("OperatorID") + user.getSalt());
			if (md5Password.compareTo(user.getPassword()) != 0) {
				resultMsg.put("OperatorID", "313744932");
				resultMsg.put("SuccStat", 1);
				resultMsg.put("FailReason", 2);
				Map<String, Object> mEncryptData = new HashMap<String, Object>();
				mEncryptData.putAll(resultMsg);
				String newdata = aesencryptionutil.encryptData(mEncryptData,mobilityasiaconfig.getDataSecret(),mobilityasiaconfig.getDataSecretIV());
				Map<String, Object> mRequest = new HashMap<String, Object>();
				mRequest.put("Ret", 0);
				mRequest.put("Data", newdata);
				mRequest.put("Msg", "");
				mRequest.put("Sig", HmacUtils.hmacMd5Hex(mobilityasiaconfig.getSigSecret(), 0 + "" + newdata).toUpperCase());
				JSONObject result = JSONObject.fromObject(mRequest);
				return result;
			}
		}
		// 拼装accessToken
		try {
			String accessToken = JwtHelper.createCharingJWT(mData.get("OperatorSecret").toString(), mData.get("OperatorID").toString(), jwtconfig.getClientId(), jwtconfig.getName(),
					jwtconfig.getExpiresSecond() * 1000, jwtconfig.getBase64Secret());
			resultMsg.put("OperatorID", "313744932");
			resultMsg.put("AccessToken", accessToken);
			resultMsg.put("TokenAvailableTime", jwtconfig.getExpiresSecond());
			resultMsg.put("SuccStat", 0);
			resultMsg.put("FailReason", 0);
			Map<String, Object> mEncryptData = new HashMap<String, Object>();
			mEncryptData.putAll(resultMsg);
			String newdata = aesencryptionutil.encryptData(mEncryptData,mobilityasiaconfig.getDataSecret(),mobilityasiaconfig.getDataSecretIV());
			Map<String, Object> mRequest = new HashMap<String, Object>();
			mRequest.put("Ret", 0);
			mRequest.put("Data", newdata);
			mRequest.put("Msg", "");
			mRequest.put("Sig", HmacUtils.hmacMd5Hex(mobilityasiaconfig.getSigSecret(), 0 + "" + newdata).toUpperCase());
			JSONObject result = JSONObject.fromObject(mRequest);
			logger.info(result.toString());
			return result;
		} catch (Exception e) {
			resultMsg.put("OperatorID", "313744932");
			resultMsg.put("SuccStat", 1);
			resultMsg.put("FailReason", "服务器异常");
			Map<String, Object> mEncryptData = new HashMap<String, Object>();
			mEncryptData.putAll(resultMsg);
			String newdata = aesencryptionutil.encryptData(mEncryptData,mobilityasiaconfig.getDataSecret(),mobilityasiaconfig.getDataSecretIV());
			Map<String, Object> mRequest = new HashMap<String, Object>();
			mRequest.put("Ret", 0);
			mRequest.put("Data", newdata);
			mRequest.put("Msg", "");
			mRequest.put("Sig", HmacUtils.hmacMd5Hex(mobilityasiaconfig.getSigSecret(), 0 + "" + newdata).toUpperCase());
			JSONObject result = JSONObject.fromObject(mRequest);
			return result;
		}
		
	}
	
	
}